<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Region;
use App\Models\Store;
use Illuminate\Http\Request;

class StoreController extends Controller
{
    protected $storeModel;
    protected $regionModel;

    public function __construct()
    {
        $this->storeModel = new Store();
        $this->regionModel = new Region();
    }

    //获取门店信息（门店页）
    public function storeListForStorePage(Request $request){
        $region = $request->input('region');

        $region_id = $this->regionModel->getInfo('name',$region)['id'];

        $res = $this->storeModel->getInfoList('region_id',$region_id);

        return $this->success($res,"门店列表已经获取成功");
    }

    public function storeListForBookPage(Request $request){
        $store = $request->input('store') ?? '五月花NewBeauty';
        $region_id = $this->storeModel->getInfo("name",$store)['region_id'];
        $storeList = $this->storeModel->getInfoList('region_id',$region_id);
        $storeNameArr = $this->toLinearArray($storeList,'name');

        foreach ($storeList as $k=>$v){
            if($v['name'] == $store ){
                unset($storeNameArr[$k]);
                array_unshift($storeNameArr, $v['name']);
            }
        }
        return $this->success($storeNameArr,'门店列表获取成功');
    }

    public function allStoreListForBookPage(Request $request){
        //获取默认的门店
        $store = $request->input('store') ?? '五月花NewBeauty';
        //获取门店所在的区域ID
        $region_id = $this->storeModel->getInfo("name",$store)['region_id'];
        //获取所有的区域
        $regionList = $this->regionModel->getInfoList();
        $regionArr = $this->toLinearArray($regionList,'id');
        //根据默认门店的区域排在数组的第一位
        foreach($regionArr as $k=>$v){
            if($region_id == $v){
                unset($regionArr[$k]);
                array_unshift($regionArr, $v);
            }
        }

        $storeNameArr = [];
        $storeAddressArr = [];
        foreach($regionArr as $key => $val){
            $rs = $this->storeModel->getInfoList('region_id',$val)->toArray();
            if($key == 0){

                foreach ($rs as $k=>$v){
                    if($v['name'] == $store){

                        array_unshift($rs,$rs[$k]);
                        unset($rs[$k+1]);
                    }

                }

                $s = $this->toLinearArray($rs,'name');
                $a = $this->toLinearArray($rs,'address');

                $storeAddressArr[] = $a;
                $storeNameArr[] = $s;
            }else{
                $storeNameArr[] = $this->toLinearArray($rs,'name');
                $storeAddressArr[] = $this->toLinearArray($rs,'address');
            }

        }

        return $this->success(['storeName'=>$storeNameArr,'storeAddress'=>$storeAddressArr]);
    }
}
